package com.lvmama.finance.demo.elasticsearch.service;

import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.lvmama.finance.demo.elasticsearch.domain.docs.ProductDoc;
import com.lvmama.finance.demo.elasticsearch.domain.jpa.ProductEntity;
import com.lvmama.finance.demo.elasticsearch.mapper.DozerMapper;
import com.lvmama.finance.demo.elasticsearch.repository.docs.ProductDocRepository;
import com.lvmama.finance.demo.elasticsearch.repository.jpa.ProductRepository;
import com.lvmama.finance.demo.elasticsearch.vo.ProductVO;

@Service
public class ProductServiceImpl implements ProductService{

	@Autowired
	private ProductRepository productRepository;
	@Autowired
	private ProductDocRepository productDocRepository;
	@Autowired
	private DozerMapper mapper;
	
	@Override
	public List<ProductVO> findAllProducts() {
		List<ProductDoc> result = new ArrayList<>();
		for (ProductDoc doc : productDocRepository.findAll()) {
			result.add(doc);
		}
		return mapper.mapToList(result, ProductVO.class);
	}

	@Override
	public ProductVO findOneProduct(Long productId) {
		return mapper.map(productDocRepository.findOne(productId), ProductVO.class);
	}

	@Override
	@Transactional
	public ProductVO addProduct(ProductVO product) {
		ProductEntity entity = null;
		if (product.getId() == null) {
			entity = mapper.map(product, ProductEntity.class);
		} else {
			entity = productRepository.findOne(product.getId());
			mapper.map(product, entity);
		}
		productRepository.save(entity);
		
		productDocRepository.save(mapper.map(entity, ProductDoc.class));
		
		return mapper.map(entity, ProductVO.class);
	}

	@Override
	@Transactional
	public void deleteProduct(Long productId) {
		productRepository.delete(productId);
		productDocRepository.delete(productId);
	}

}
